package com.iso8583.util;

import com.iso8583.Iso8583Parser;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Map;

/**
 * Created by Administrator on 2015/6/30.
 */
public class PosUtil {
    /**
     * 网服务器发送请求
     */
    public static byte[] sendPosMsg(byte[] request, String host, Integer port) {
        long start ,end  = 0;
        byte[] buf = null;

        Socket socket=new Socket();
        try {
            socket.setKeepAlive(true);
            socket.connect(new InetSocketAddress(host, port));
            start = System.currentTimeMillis();

            if(socket.isConnected()){
                System.out.println("socket 建立成功！ ");
            }

            OutputStream out = socket.getOutputStream();
            out.write(request);
            out.flush();

            //两字节长度
            byte[] lenbuf = new byte[2];
            while (socket != null && socket.isConnected()) {
                if (socket.getInputStream().read(lenbuf) == 2) {
                    //计算前两位报文所表示的报文长度
                    int size = computeLength(lenbuf);
                    System.out.println("响应报文长度："+size);
                    //新建对应长度字节数组
                    buf = new byte[size];
                    //读取数据
                    socket.getInputStream().read(buf);
                    System.out.println("接收到的byte数组：");
                    for(int i=0;i<buf.length;i++){
                        System.out.print(buf[i] + ",");
                    }
                    break;
                }
            }
            end = System.currentTimeMillis();
            System.out.println();
            System.out.println("交易处理时间： " + (end - start)+" 毫秒...");
            out.close();
            socket.close();
        }catch (SocketTimeoutException e) {
            System.out.println("等待响应超时...");
        } catch (SocketException e) {
            System.out.println("socket异常...");
        } catch (IOException e) {
            System.out.println("IO异常...");
        }
        return buf;
    }

    public static int computeLength(byte[] lenBts){
        if(lenBts.length!=2){
            throw new IllegalArgumentException("字节长度不正确，预期值为2，实际值为："+lenBts.length);
        }
        return (lenBts[0] & 0xff) * 256
                + (lenBts[1] & 0xff);
    }
    /**
     * 解析返回的报文
     */
    public static void analysis8583(String respond) throws Exception {
        JSONObject jsonObject = new JSONObject();
        byte[] bytes = ByteUtils.hexStringToByte(respond);

        Map<String, String> map = Iso8583Parser.parser("POS", bytes, true);
        //测试打印
        System.out.println("开始打印报文数据：");
        for (String key:map.keySet()){
            if ("TPDU".equals(key)) {
                String value = map.get(key);//tpdu

            }
            String value = map.get(key);
            jsonObject.put(key,value);
            System.out.println("\t"+"domain="+key+"," + "\t " + "value="+value);
        }
    }
    /**
     * 解析响应报文
     */
    public static void parse8583(String xml, String respond) throws Exception{
        JSONObject jsonObject = new JSONObject();
        byte[] bytes = ByteUtils.hexStringToByte(respond);
        Map<String, String> map = Iso8583Parser.parse(xml, bytes, true);
        System.out.println("开始打印报文数据：");
        for (String key:map.keySet()){
            if ("TPDU".equals(key)) {
                String value = map.get(key);//tpdu

            }
            String value = map.get(key);
            jsonObject.put(key,value);
            System.out.println("\t"+"domain="+key+"," + "\t " + "value="+value);
        }
    }

    /**
     * 处理返回的金额
     * @param field54
     * @return
     */
    public static String  handleBalance(String field54){
        String ACCOUNT_TYPE = "";		//帐户类型(10:储蓄帐户,30:信用卡帐户)
        //String AMOUNT_TYPE = "";		//数量类型(02:可用佘额)
        String CURRENCY_CODE = "";	//货币代码(156:人民币,其它:美元)
        String AMOUNT_SIGN = "";		//余额符号(C:正,其它:负)
        Double AMOUNT = 0.00;			//佘额(12位表示,分为单位)
        String AmountStr = "";
        ACCOUNT_TYPE = field54.substring(0, 2);
        //AMOUNT_TYPE=value.substring(2, 4);
        CURRENCY_CODE = field54.substring(4,7);
        AMOUNT_SIGN = field54.substring(7, 8);
        AMOUNT = Double.parseDouble(field54.substring(8))/100;
        if(ACCOUNT_TYPE.equals("10"))
        {
            AmountStr+="储蓄帐户 ";
        }else if(ACCOUNT_TYPE.equals("30"))
        {
            AmountStr+="信用卡帐户 ";
        }
        if(CURRENCY_CODE.equals("156"))
        {
            AmountStr+="￥";
        }else{
            AmountStr+="$";
        }
        if(!AMOUNT_SIGN.equals("C"))
        {
            AmountStr+="-";
        }
        AmountStr+=AMOUNT;
        return AmountStr;
    }

}
